<template>
	<view class="purchasing">
		<view class="header">
			<view class="form">
				<view class="select">
					<view class="text">
						<text class="text-icon">*</text>
						<text class="text-name">选择供应商:</text>
					</view>
					<view class="select-input">
						<view class="select-input-left">
							<!-- <text v-if="supplierList && supplierList[supplierListIndex]">{{
									supplierList[supplierListIndex].sname }}</text>
								<text v-else>请选择</text> -->
							<input type="text" v-model="sname" placeholder="请选择或输入">
							<view @tap="open" class="changeBtn">
								选择
							</view>
						</view>
						<!-- <picker range-key="sname" @change="supplierChange" :value="supplierListIndex"
							:range="supplierList">
							<u-icon name="arrow-down" color="#272727" size="24rpx"></u-icon>
						</picker> -->
					</view>
				</view>
				<view class="select">
					<view class="text">
						<text class="text-icon">*</text>
						<text class="text-name">选择日期:</text>
					</view>
					<view class="select-input">
						<view class="select-input-left">
							<!-- <text v-if="supplierList && supplierList[supplierListIndex]">{{
									supplierList[supplierListIndex].sname }}</text>
								<text v-else>请选择</text> -->
							<input disabled type="text" v-model="payDay" placeholder="请选择">
							<view @tap="showDate = true" class="changeBtn">
								选择
							</view>
						</view>
						<!-- <picker range-key="sname" @change="supplierChange" :value="supplierListIndex"
							:range="supplierList">
							<u-icon name="arrow-down" color="#272727" size="24rpx"></u-icon>
						</picker> -->
					</view>
				</view>
			</view>
		</view>

		<view class="article">
			<view class="title">
				<view class="text">货物清单</view>
				<view @tap="goAdd" class="add_btn">添加产品</view>
			</view>
			<table border="0">
				<tr>
					<th>产品</th>
					<th>单价</th>
					<th>数量</th>
					<th>金额</th>
					<!-- <th>操作</th> -->
				</tr>
				<block v-if="list.length > 0">
					<tr style="height: 40px;" @longtap="edit(item, index)" v-for="(item, index) in list" :key="index">
						<td>{{ item.matName || item.matId || '0' }}</td>
						<td>{{ item.realPrice || '0' | unifyNumber}}</td>
						<td>{{ item.orderNum || '0' }}</td>
						<td>{{ item.orderNum * item.realPrice || 0 | unifyNumber}}</td>
						<!-- <td>
							<view class="btns">
								<view class="button-mini" @tap="edit(item, index)">编辑</view>
								<view class="button-mini" @tap="del(index)">删除</view>
							</view>
						</td> -->
					</tr>
					<tr>
						<td></td>
						<td></td>
						<td colspan="3">
							总金额:
							<text class="price">{{ priceTotal || 0 | unifyNumber}}</text>
						</td>
					</tr>
				</block>

				<tr v-else>
					<!-- #ifndef MP-WEIXIN -->
					<td colspan="7">
						<u-divider textSize="34" text="暂无数据"></u-divider>
					</td>
					<!-- #endif -->
					<!-- #ifdef MP-WEIXIN -->
					<td style=" position: absolute;left: 20rpx;right: 20rpx;">
						<u-divider textSize="34" text="暂无数据"></u-divider>
					</td>
					<td style="height: 100rpx;"></td>
					<td></td>
					<td></td>
					<!-- #endif -->
				</tr>
			</table>
		</view>
		<u-gap height="88"></u-gap>
		<view class="footer_btn">
			<!-- <view class="button-primary">核算金额</view> -->
			<view @tap="submit" class="button-primary">提交订单</view>
		</view>
		<Supper ref="child" @saveUser="saveUser" />
		<myDatePick mode="date" @bindDateChange="bindDateChange" :show.sync="showDate"></myDatePick>
	</view>
</template>

<script>
	import Supper from "../../components/supper.vue"
	import myDatePick from "../../components/myDatePick.vue"
	export default {
		data() {
			return {
				query: {
					pageNo: 1,
					pageSize: 15,
					sid: '' // 供应商id
				},
				sid: '',
				showDate: false,
				sname: "",
				list: [],
				total: 0,
				supplierList: [],
				supplierListIndex: undefined,
				priceTotal: 0,
				payDay:  uni.$u.timeFormat(Date.now(), 'yyyy-mm-dd')
			};
		},
		watch: {
			list: {
				handler(newData) {
					if (newData && newData.length) {
						let total = 0
						// let total = newData.reduce((prev, cur) => {
						// 	// console.log(prev, cur.total)
						// 	return (parseFloat(prev) + parseFloat(cur.total)).toFixed(2);
						// }, 0);
						newData.map(item => {
							item.total = item.total || 0
							total += +item.total

						})
						// console.log(newData,"newData");
						// console.log(total)
						this.priceTotal = total;
					} else {
						this.priceTotal = 0;
					}
				},
				immediate: true,
				deep: true
			}
		},
		onLoad() {
			// this.getList(true);
			this.supplierListApi();
			this.$nextTick(() => {
				this.open()
			})
		},
		components: {
			Supper,
			myDatePick
		},
		async onShow() {
			await this.create();
			await this.getList(true)
			// console.log(this.list);

		},
		onReachBottom() {
			if (this.list.length < this.total) {
				this.getList();
			}
		},
		onUnload() {
			uni.removeStorageSync('purchaseEntryList');
		},
		methods: {
			bindDateChange(e) {
				this.payDay = e
			},
			open() {
				this.$refs.child.open();
			},
			saveUser(data) {
				this.sname = data.cname;
				this.sid = data.cid;
				this.$refs.child.close();

			},
			goAdd() {
				// if (!this.sid) {
				// 	uni.showToast({
				// 		title: "请选择供应商！",
				// 		icon: "none"
				// 	})
				// 	return
				// }
				this.skip(`/pages/purchasing/addProduct?sid=${this.sid}`)
			},
			edit(e, index) {
				uni.$u.route({
					type: 'navigateTo',
					url: 'pages/purchasing/addProduct',
					params: {
						index,
						matId: e.matId || '',
						matName: e.matName || '',
						realPrice: e.realPrice || '',
						orderNum: e.orderNum || ''
					}
				});
			},
			del(index) {
				uni.showModal({
					title: '删除',
					content: '确定删除',
					success: res => {
						if (res.confirm) {
							let list = uni.$u.deepClone(this.list);
							list.splice(index, 1);
							uni.setStorageSync('purchaseEntryList', JSON.stringify(list));
							this.create();
						}
					}
				});
			},
			create() {
				let list = uni.getStorageSync('purchaseEntryList') ? JSON.parse(uni.getStorageSync('purchaseEntryList')) :
					[];
				// console.log(list);
				this.list = list;
			},
			async submit() {
				if (!this.sname) {
					uni.showToast({
						title: '选择供应商',
						icon: 'none'
					});
					return;
				}
				if (!this.payDay) {
					uni.showToast({
						title: '选择时间',
						icon: 'none'
					});
					return;
				}
				if (!this.list || !this.list.length) {
					uni.showToast({
						title: '选择添加产品',
						icon: 'none'
					});
					return;
				}

				let details = [];
				this.list.map(e => {
					details.push({
						matId: e.matId,
						orderNum: +e.orderNum || 1,
						realPrice: +e.realPrice || 0
					});
				});


				await this.$api
					.orderPurchaseAdd({
						details,
						sname: this.sname,
						payDay: this.payDay
					})
				uni.showToast({
					title: '提交成功',
					icon: 'none',
					mask: true
				});


                const pages = getCurrentPages();
                const prePage = pages[pages.length - 2];
                if (prePage && prePage.route.indexOf(
                        '/purchasing/supplier') !== -1) {
                    prePage['$vm'].getList && prePage['$vm'].getList(true);
                }
                uni.navigateBack();


			},
			getList(first) {
				this.create()
				// uni.showLoading({
				// 	title: '加载中...'
				// });

				// if (this.supplierListIndex !== undefined) {
				// 	this.query.sid = this.supplierList[this.supplierListIndex].sid;
				// }

				// let query = uni.$u.deepClone(this.query);
				// if (first) {
				// 	// this.list = [];
				// 	this.create()
				// 	query.pageNo = 1;
				// } else {
				// 	query.pageNo += 1;
				// }
				// console.log(this.query, "query");
				// this.$api.materialPage({
				// 	data: query
				// }).then(res => {
				// 	uni.hideLoading();
				// 	if (res.result.list && res.result.list.length) {
				// 		this.query.pageNo = query.pageNo;
				// 		let list = res.result.list;
				// 		this.list = [...this.list, ...list];
				// 	}
				// 	this.total = res.result.total;
				// });
			},
			supplierChange(e) {
				this.supplierListIndex = e.detail.value;
				this.sid = this.supplierList[this.supplierListIndex].sid;
				this.sname = this.supplierList[this.supplierListIndex].sname;
				this.getList(true);
			},
			supplierListApi() {
				this.$api
					.supplierListApi({
						pageNo: 1,
						pageSize: 999
					})
					.then(res => {
						this.supplierList = res.result.list || [];
						// if (this.supplierList && this.supplierList.length) {
						// 	this.supplierListIndex = 0;
						// 	this.getList(true);
						// } else {
						// 	uni.showToast({
						// 		title: '供应商数据为空',
						// 		icon: 'none'
						// 	});
						// }
					});
			}
		},

	};
</script>

<style lang="scss" scoped>
	.purchasing {
		min-height: calc(100vh - 44px - env(safe-area-inset-top));

		.price {
			color: #fe3430;
		}

		.header {
			padding: 16rpx 29rpx;
			background-color: #fff;
		}

		.btns {
			display: flex;
			flex-direction: column;

			.button-mini {
				// flex: 1;
				margin: 6rpx auto;
				width: 100rpx;
			}
		}

		.form {
			.select {
				.text {
					margin: 20rpx 0;
					color: #bdbdbd;

					.text-icon {
						color: #fe3430;
					}

					.text-name {
						margin-left: 10rpx;
					}
				}

				input,
				.select-input {
					width: 100%;
					height: 94rpx;
					// background: #f2f2f2;
					border-radius: 47rpx;
				}

				.select-input {
					font-size: 30rpx;
					color: #272727;
					padding: 0 36rpx;
					display: flex;
					align-items: center;

					.select-input-left {
						display: flex;
						justify-content: space-between;
						align-items: center;
						flex: 1;

						.changeBtn {
							background-color: #fe3430;
							width: 150rpx;
							margin-left: 20rpx;
							color: #fff;
							text-align: center;
							height: 80rpx;
							line-height: 80rpx;
							border-radius: 40rpx;
						}

						input {
							background: #f2f2f2;
							text-indent: 1em;
						}
					}
				}

				.input {
					display: flex;
					align-items: center;
					justify-content: space-between;

					input {
						width: 271rpx;
					}

					text {
						text-align: left;
					}
				}
			}
		}
	}

	.article {
		padding: 32rpx 20rpx;

		.title {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding-bottom: 30rpx;

			.text {
				font-size: 36rpx;
				font-family: Microsoft YaHei;
				font-weight: 400;
				color: #272727;
			}

			.add_btn {
				height: 60rpx;
				line-height: 60rpx;
				background: #fe3430;
				border-radius: 29rpx;
				color: #fff;
				padding: 0 20rpx;
			}
		}

		.price {
			margin-left: 16rpx;
			color: #fe3430;
		}

		table {
			border-radius: 20rpx;
			background-color: #fff;
			width: 100%;
			th {
				padding: 32rpx 0;
				border-bottom: 2rpx solid #f1f1f1;

				&:last-child {
					width: 130rpx;
				}
			}

			td {
				// padding: 32rpx 0;
				text-align: center;
			}
		}
	}

	.divider {
		width: 100%;
	}

	.footer_btn {
		display: flex;
		justify-content: space-around;
		position: absolute;
		bottom: 44px;
		width: 100%;
		left: 0;

		.button-primary {
			width: 280rpx;
		}
	}
</style>